package jsp;

import util.CookieUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求中的表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 进入数据库查询,判断用户输入的用户名与密码是否正确
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ums?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();
            if (rs.next()) {
                // 如果查询到结果了,则说明用户输入的的用户名与密码正确
                // 将正确的用户名与密码保存到Cookie中
                // 默认保存1天
                CookieUtil.addCookie("username", username, 24 * 60 * 60, resp);
                CookieUtil.addCookie("password", password, 24 * 60 * 60, resp);
                // 登录成功之后,页面跳转到主页
                req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
                return;
            }
            // 如果没有进入分支,说明没有查询到结果,即:用户名或密码错误
            // 返回错误信息
            req.setAttribute("loginMsg","用户名或密码错误");
            req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
